package com.suliao.common.util;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author： M1nG
 * @since： 2020/9/22 17:06
 * @description：
 * @version： 1.0
 */
@Component
@Slf4j
@NoArgsConstructor
public class OSSUtil {

    //当前日期的格式化用于创建子文件夹
    private DateTimeFormatter yyyyMM = DateTimeFormatter.ofPattern("yyyyMM");

    //远程阿里云的地址
    @Value(value = "${aliyun.oss.end-point:oss-cn-shanghai.aliyuncs.com}")
    private String endPoint;
    //阿里云的远程登录id
    @Value(value = "${aliyun.oss.access-key-id:LTAI4GHQvKSXa6xGDQS4gsSp}")
    private String accessKeyId;
    //远程登录的密钥
    @Value(value = "${aliyun.oss.access-key-secret:NUix9IZRvo2R0xlLhxhXmFibz0Uq5k}")
    private String accessKeySecret;
    //上传到OSS服务器上区域的名称
    @Value(value = "${aliyun.oss.bucket-name:suliao-web}")
    private String bucketName;
    //图像的文件夹
    @Value(value = "${aliyun.oss.img-folder:img/}")
    private String imgFolder;
    //文件的文件夹
    @Value(value = "${aliyun.oss.file-folder:file/}")
    private String fileFolder;
    //上传文件的最大限定值
    @Value(value = "${aliyun.oss.img-max-size:10485760}")
    private Long imgMaxSize;


    /**
     * oss 上传
     * 如果返回的url是null 则代表上传失败
     * @param multipartFile 文件对象
     * @return null or String:FileTypeName
     */
    public String upLoad(MultipartFile multipartFile) {
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        String url = null;
        try {
            String filename = multipartFile.getOriginalFilename();
            String fileTypeName = getFileTypeName(filename);
            LocalDate date = LocalDate.now();
            String uuid = IdUtil.simpleUUID();
            if (fileTypeName == null) {
                new Exception("上传文件类型有误！");
            }
            String baseFolder;
            if (judgeImgType(fileTypeName)) {
                baseFolder = imgFolder;
            } else {
                baseFolder = fileFolder;
            }
            final String folderName = baseFolder + date.format(yyyyMM) + "/";
            if (!ossClient.doesObjectExist(bucketName, folderName)) {
                ossClient.putObject(bucketName, folderName, new ByteArrayInputStream(new byte[0]));
            }
            final String fileName = folderName + uuid + "." + fileTypeName;
            ossClient.putObject(bucketName, fileName, multipartFile.getInputStream());
            url = "https://" + bucketName + "." + endPoint + "/" + fileName;
        } catch (OSSException oe) {
            oe.printStackTrace();
            log.error("Error Message" + oe.getErrorMessage());
        } catch (ClientException ce) {
            ce.printStackTrace();
            log.error("Error Message: " + ce.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Error Message: " + e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return url;
    }


    /**
     * 获取文件的后缀名
     *
     * @param fileName 键
     * @return null or String:FileTypeName
     */
    private String getFileTypeName(String fileName) {
        int lastIndexOf = fileName.lastIndexOf(".");
        if (lastIndexOf == -1) {
            return null;
        } else {
            return fileName.substring(fileName.lastIndexOf(".") + 1);//获取文件的后缀名
        }
    }


    /**
     * 根据文件后缀名去判断是否为图片类型
     *
     * @param fileTypeName 文件的名称
     * @return boolean
     */
    private static boolean judgeImgType(String fileTypeName) {
        if (fileTypeName.equalsIgnoreCase("jpg")) {
            return true;
        } else if (fileTypeName.equalsIgnoreCase("png")) {
            return true;
        } else if (fileTypeName.equalsIgnoreCase("jpeg")) {
            return true;
        } else if (fileTypeName.equalsIgnoreCase("gif")) {
            return true;
        } else if (fileTypeName.equalsIgnoreCase("bmp")) {
            return true;
        } else {
            log.info("非图像文件类型！");
            return false;
        }
    }

    /**
     * 获取改变分辨率大小的url
     *
     * @param oriUrl 原始url
     * @param width  宽度  0为不设置
     * @param height 高度 0为不设置
     * @return boolean
     */
    public static String getUrlByResize(String oriUrl, int width, int height) {
        if (oriUrl == null || !oriUrl.toLowerCase().startsWith("https:")) {
            return oriUrl;
        }
        StringBuffer result = new StringBuffer();
        result.append(oriUrl);
        result.append("?x-oss-process=image/resize");
        result.append(width == 0 ? "" : ",w_" + width);
        result.append(height == 0 ? "" : ",h_" + height);
        return result.toString();
    }
}